<?php
namespace app\admin\model;
use app\common\model\CommonModel;
use app\common\model\Category;
use app\common\model\Supplier;
use app\common\model\OrderGoods;
use app\common\model\Goods;
use app\common\model\Stock;
use app\common\model\Shop;
use think\Session;
use think\Db;

class GoodsModel extends CommonModel
{
	/**
    * 获取商品信息
    */
    public static function getGoods($info)
    {
        $where = [];
        /*产品子分类*/
		if($info['shop_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['g.shop_id'] = $info['shop_id'];
		}
        /*时间区间*/
        if($info['start'] != '' || $info['end'] != '')
		{
			if($info['start'])
			{
				$where['g.addtime'][] = ['>',strtotime($info['start'])];
			}
			if($info['end'])
			{
				$where['g.addtime'][] = ['<',strtotime($info['end'])];
			}
		}else{
            /*上月、当前月*/
            if(array_key_exists('shijian',$info))
            {
                if($info['shijian'] != '')
                {
                    if($info['shijian'] == CommonModel::NUMBER_ZERO)
                    {
                        $where['g.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                        $where['g.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
                    }else{
                        $where['g.addtime'][] = ['>',mktime(0, 0, 0,date('m')-1,1,date('Y'))];
                        $where['g.addtime'][] = ['<',mktime(0, 0, 0,date('m'),0,date('Y'))];
                    }
                }
            }else{
                $where['g.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                $where['g.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
            }
        }
        $Stock = new Stock();
        $Category = new Category();
        $field = 'g.goods_id,g.goods_name,g.category_id,g.cat_id,g.brand_name,g.memory_name,g.attribute_name,g.colour_name,g.marker,g.unit,g.selling_price,g.trade_price,s.buying_price';
        $list = $Stock->getStockList($where,$field,10,$info['page'],'g.goods_id');
        foreach($list['data'] as $i=>$vo)
        {
            $where1['goods_id'] = $vo['goods_id'];
            $where1['state'] = 0;
            /*入库数量*/
            $list['data'][$i]['number'] = $Stock->stockNumber($where1);
            $list['data'][$i]['category_id'] = $Category->getCategoryField(['category_id'=>$vo['category_id']],'category_name');
            $list['data'][$i]['cat_id'] = $Category->getCategoryField(['category_id'=>$vo['cat_id']],'category_name');
        }
        return $list;
    }
    /**
    * 商品列表
    */
    public static function goodsList($info)
    {
       $where = self::is_where($info);
       $list = (new Goods)->getGoodsList($where,10,$info['page']);
       $Stock = new Stock();
       foreach($list['data'] as $i=>$vo)
       {
            $where1['goods_id'] = $vo['goods_id'];
            $where1['state'] = 0;
            /*入库数量*/
            $list['data'][$i]['number'] = $Stock->stockNumber($where1);
       }
       return $list;
    }
    /**
	* where 整理
	*/
	private function is_where($info)
	{
		$where = [];
        /*产品属性*/
		if($info['attribute_name'] != '' && $info['attribute_name'])
		{
			$where['attribute_name'] = $info['attribute_name'];
		}
        /*产品品牌*/
		if($info['brand_name'] != '' && $info['brand_name'])
		{
			$where['brand_name'] = $info['brand_name'];
		}
        /*产品子分类*/
		if($info['cat_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['cat_id'] = $info['cat_id'];
		}
        /*产品分类*/
		if($info['category_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['category_id'] = $info['category_id'];
		}
        /*产品颜色*/
		if($info['colour_name'] != '' && $info['colour_name'])
		{
			$where['colour_name'] = $info['colour_name'];
		}
        /*产品内存*/
		if($info['memory_name'] != '' && $info['memory_name'])
		{
			$where['memory_name'] = $info['memory_name'];
		}
        /*门店*/
		if($info['shop_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['shop_id'] = $info['shop_id'];
		}
        /*关键字搜索*/
		if($info['sreach'])
		{
			$where['goods_name|abbreviation|goods_sn'] = ['like','%'.$info['sreach'].'%'];
		}
       
		return $where;
	}
    /**
    * 库存详情
    */
    public static function getStockList($info)
    {
        $Supplier = new Supplier();
        $Stock = new Stock();
        $Shop = new Shop();
        
        $where['s.goods_id'] = $info['id'];
        $where['s.state'] = ['IN','0,1'];
        $where['s.period_time'] = ['>=',strtotime(date('Y-m-d',time()))];
        /*产品店铺*/
		if($info['shop_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['g.shop_id'] = $info['shop_id'];
		}
        /*关键字搜索*/
		if($info['sreach'])
		{
			$where['g.goods_name|g.abbreviation|g.goods_sn'] = ['like','%'.$info['sreach'].'%'];
		}

        $field = 's.stock_id,g.goods_name,s.imei,s.sn,s.period_time,g.shop_id,s.position,s.remarks,g.selling_price,g.trade_price,s.buying_price,s.supplier_id,s.contract_sn';
        $list = $Stock->getStockList($where,$field,10,$info['page']);
        foreach($list['data'] as $i=>$vo)
        {
            $list['data'][$i]['shop_id'] = $Shop->shopField(['shop_id'=>$vo['shop_id']],'shop_name');
            $list['data'][$i]['position'] = "【{$vo['position']}】{$vo['remarks']}";
            $list['data'][$i]['period_time'] = date('Y/m/d',$vo['period_time']);
            $list['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
        }
        return $list;
    }
    /**
    * 产品信息
    */
    public static function goodsinformation($id)
    {
        $goods = Goods::get($id);
        $where['goods_id'] = $id;
        $where['state'] = 0;
        $data['number'] = (new Stock())->stockNumber($where);
        $data['goods_name'] = $goods['goods_name'];
        $data['unit'] = $goods['unit'];
        return $data;
    }
    /**
    * 入库信息
    */
    public static function stockGoodsList($info)
    {
        $Supplier = new Supplier();
        $Stock = new Stock();
        $Shop = new Shop();
        
        $where = [];
        $whereone = self::is_where($info);
        if($whereone)
		{
			foreach($whereone as $key=>$value)
			{
				$where['g.' . $key] = $value;
			}
		}
        $where_time = self::is_show_time($info);
        if($where_time)
		{
			foreach($where_time as $key=>$value)
			{
				$where['s.' . $key] = $value;
			}
		}
        $where['s.state'] = ['IN','0,1'];
        $field = 's.stock_id,g.goods_name,g.shop_id,s.addtime,s.pur_number,s.number,g.unit,s.buying_price,s.supplier_id,s.contract_sn';
        $list = $Stock->getStockList($where,$field,10,$info['page']);
        foreach($list['data'] as $i=>$vo)
        {
            $list['data'][$i]['shop_id'] = $Shop->shopField(['shop_id'=>$vo['shop_id']],'shop_name');
            $list['data'][$i]['addtime'] = date('Y-m-d H:i',$vo['addtime']);
            $list['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
            $list['data'][$i]['total_money'] = (intval($goods['pur_number']) * intval(strval($goods['buying_price'] * 100)))/100;
        }
        return $list;
    } 
    /**
    * 逾期产品
    */
    public static function overdue($info)
    {
        $Supplier = new Supplier();
        $Shop = new Shop();
        
        $where = [];
        $whereone = self::is_where($info);
        if($whereone)
		{
			foreach($whereone as $key=>$value)
			{
				$where['g.' . $key] = $value;
			}
		}
        $where['s.state'] = ['IN','0,1'];
        $where['s.period_time'] = ['<',strtotime(date('Y-m-d',time()))];
        $field = 's.stock_id,g.goods_name,s.imei,s.sn,s.period_time,g.shop_id,g.selling_price,g.trade_price,s.buying_price,s.supplier_id,s.contract_sn,s.position,s.remarks';
        $list = (new Stock())->getStockList($where,$field,10,$info['page']);
        foreach($list['data'] as $i=>$vo)
        {
            $list['data'][$i]['shop_id'] = $Shop->shopField(['shop_id'=>$vo['shop_id']],'shop_name');
            $list['data'][$i]['period_time'] = date('Y/m/d',$vo['period_time']);
            $list['data'][$i]['position'] = "【{$vo['position']}】{$vo['remarks']}";
            $list['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
        }
        return $list;
    }
    /**
    * 入库信息详情
    */
    public static function stockGoodsInfo($info)
    {
        $where['s.stock_id'] = $info['id'];
        $field = 'g.shop_id,s.addtime,g.goods_name,g.category_id,g.cat_id,g.brand_name,g.marker,g.memory_name,g.attribute_name,g.colour_name,g.unit,g.goods_id,s.pur_number,s.buying_price,s.supplier_id,s.state,s.period_time';
        $stockList = (new Stock())->stockList($where,$field,'s.stock_id','find');
        $stockList['shop_id'] = (new Shop())->shopField(['shop_id'=>$stockList['shop_id']],'shop_name'); 
        $stockList['category_id'] = (new Category())->getCategoryField(['category_id'=>$stockList['category_id']],'category_name');
        $stockList['cat_id'] = (new Category())->getCategoryField(['category_id'=>$stockList['cat_id']],'category_name');
        $stockList['supplier_id'] = (new Supplier())->fieldSuppliers(['supplier_id'=>$stockList['supplier_id']],'supplier_name');
        $stockList['total_money'] = (intval($stockList['pur_number']) * intval(strval($stockList['buying_price'] * 100)))/100;
        if($stockList['state'] == 0)
        {
            if($stockList['period_time'] < time())
            {
                $stockList['state'] = 2;
            }
        }
        return $stockList;
    }
    /**
    * 商品库存列表
    */
    public static function gstockList($info)
    {
        $where['s.goods_id'] = $info['id'];
        $where['s.state'] = ['IN','0,1'];
        $where['s.period_time'] = ['>=',strtotime(date('Y-m-d',time()))];
        $field = 's.stock_id,g.goods_name,s.imei,s.sn,s.period_time,s.number,g.unit,s.buying_price,s.supplier_id,s.contract_sn,s.position,s.remarks';
        $list = (new Stock())->getStockList($where,$field,10,$info['page']);
        $Supplier = new Supplier();
        foreach($list['data'] as $vo)
        {
            $list['data'][$i]['position'] = "【{$vo['position']}】{$vo['remarks']}";
            $list['data'][$i]['period_time'] = date('Y/m/d',$vo['period_time']);
            $list['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
        }
        return $list;
    }
    /**
    * 退货召回库存
    */
    public static function stockLossList($info)
    {
        $Supplier = new Supplier();
        $Shop = new Shop();
        
        $where = [];
        $whereone = self::is_where($info);
        if($whereone)
		{
			foreach($whereone as $key=>$value)
			{
				$where['g.' . $key] = $value;
			}
		}
        /*供应商*/
		if($info['supplier_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['s.supplier_id'] = $info['supplier_id'];
		}
        /*状态*/
		if($info['state'] != CommonModel::NUMBER_ZERO)
		{
			$where['s.state'] = $info['state'];
		}else{
            $where['s.state'] = ['IN','3,4'];
        }
        $where['s.is_show'] = 0;
        $where['s.headquarters'] = 1;
        $field = 's.stock_id,s.state,g.goods_name,s.imei,s.sn,s.period_time,g.shop_id,g.selling_price,g.trade_price,s.buying_price,s.supplier_id,s.contract_sn,s.position,s.remarks';
        $list = (new Stock())->getStockList($where,$field,10,$info['page']);
        foreach($list['data'] as $i=>$vo)
        {
            $list['data'][$i]['state'] = $vo['state']==3?'退货':'召回';
            $list['data'][$i]['shop_id'] = $Shop->shopField(['shop_id'=>$vo['shop_id']],'shop_name');
            $list['data'][$i]['period_time'] = date('Y/m/d',$vo['period_time']);
            $list['data'][$i]['position'] = "【{$vo['position']}】{$vo['remarks']}";
            $list['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
        }
        return $list;
    }
     /**
    * 报损库存
    */
    public static function stockLossList1($info)
    {
        $Supplier = new Supplier();
        $Shop = new Shop();
        
        $where = [];
        $whereone = self::is_where($info);
        if($whereone)
		{
			foreach($whereone as $key=>$value)
			{
				$where['g.' . $key] = $value;
			}
		}
        /*状态*/
        $where['s.state'] = 2;
        $where['s.is_show'] = 0;
        $where['s.headquarters'] = 1;
        $field = 's.stock_id,g.goods_name,g.shop_id,g.unit,s.news_name,s.number,s.imei,s.sn,s.period_time,s.buying_price,s.contract_sn,s.supplier_id';
        $list = (new Stock())->getStockList($where,$field,10,$info['page']);
        foreach($list['data'] as $i=>$vo)
        {
            $list['data'][$i]['shop_id'] = $Shop->shopField(['shop_id'=>$vo['shop_id']],'shop_name');
            $list['data'][$i]['period_time'] = date('Y/m/d',$vo['period_time']);
            $list['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
        }
        return $list;
    }
    /**
    * 时间条件
    */
    private function is_show_time($info)
    {
        $where = [];
        /*时间区间*/
        if($info['start'] != '' || $info['end'] != '')
		{
			if($info['start'])
			{
				$where['addtime'][] = ['>',strtotime($info['start'])];
			}
			if($info['end'])
			{
				$where['addtime'][] = ['<',strtotime($info['end'])];
			}
			return $where;
		}
        /*上月、当前月*/
        if(array_key_exists('shijian',$info))
        {
            if($info['shijian'] != '')
            {
                if($info['shijian'] == CommonModel::NUMBER_ZERO)
                {
                    $where['addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                    $where['addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
                }else{
                    $where['addtime'][] = ['>',mktime(0, 0, 0,date('m')-1,1,date('Y'))];
                    $where['addtime'][] = ['<',mktime(0, 0, 0,date('m'),0,date('Y'))];
                }
            }
        }else{
            $where['addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
            $where['addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
        }
        return $where;
    }
    /**
    * 确认退货
    */
    public static function recoveryStock($info)
    {
        $where['stock_id'] = ['in',$info['ids']];
        $data['is_show'] = 1;
        if((new Stock())->updateStorage($where,$data) === false)
        {
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 返回门店
    */
    public static function returnStock($info)
    {
        /*开启事物*/
		Db::startTrans();
		$Stock = new Stock();
		/*获取库存信息*/
		$stockList = $Stock->stockList(['s.stock_id'=>['in',$info['ids']]],'stock_id,fid,number');
		foreach($stockList as $vo)
		{
			/*修改父级库存信息*/
			$data['state'] = CommonModel::NUMBER_ZERO;
			$data['number'] = ['inc',$vo['number']];
			if($Stock->updateStorage(['stock_id'=>$vo['fid']],$data) === false)
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
			/*关闭当前库存信息*/
			if($Stock->updateStorage(['stock_id'=>$vo['stock_id']],['is_show'=>1]) === false)
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
		}
		
		Db::commit();
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 产品历史
    */
    public static function historyGoods($info)
    {
        $where1 = self::is_where($info);
        $list = (new Goods())->getGoodsList($where1,10,$info['page']);
        $OrderGoods = new OrderGoods();
        $Stock = new Stock();
        foreach($list['data'] as $i=>$vo)
        {
            $where['goods_id'] = $vo['goods_id'];
            $where['state'] = 0;
            /*入库数量*/
            $list['data'][$i]['ruku'] = $Stock->stockNumber($where);
            /*退货数量*/
            $where['state'] = 3;
            $list['data'][$i]['tuihuo'] = $Stock->stockNumber($where);
            /*召回数量*/
            $where['state'] = 4;
            $list['data'][$i]['zhaohui'] = $Stock->stockNumber($where);
            /*销售数量*/
            unset($where['state']);
            $where['is_show'] = 0;
            $list['data'][$i]['xiaoshou'] = $OrderGoods->orderGoodsNumber($where,'number');
            /*总营业额（元）*/
            $list['data'][$i]['yingyee'] = $OrderGoods->orderGoodsNumber($where,'goods_money');
            /*总成本（元）*/
            $list['data'][$i]['chengben'] = $OrderGoods->orderGoodsNumber($where,'cost_money');
            /*总盈利（元）*/
            $list['data'][$i]['yingli'] = $OrderGoods->orderGoodsNumber($where,'profit_money');
        }
        return $list;
    }
}
